import { LoginParams, TokenInfo, UserInfo } from "@scpun/core";
import { useLoading } from "@scpun/hooks";
import { defineStore, resetAllStores, useAccessStore, useOAuth2Store } from "@scpun/stores";
import { useRouter } from "vue-router";
import { loadByUsername, logout as LOGOUT } from "/@/api/oauth2";
import { PageEnum } from "/@/router";

export const useAuthenticationStore = defineStore("authentication-store", () => {
    const accessStore = useAccessStore();
    const oauth2Store = useOAuth2Store();
    const router = useRouter();

    const { loading, startLoading, endLoading } = useLoading();

    /**
     * 异步处理登录操作
     * Asynchronously handle the login process
     * @param params 登录表单数据
     */
    async function authLogin(params: LoginParams, onSuccess?: () => Promise<void> | void): Promise<Nullable<UserInfo>> {
        // 异步处理用户登录操作并获取 accessToken
        let userInfo: null | UserInfo = null;
        try {
            startLoading();
            const tokenInfo: TokenInfo = await loadByUsername({
                ...params,
            });

            // 如果成功获取到 accessToken
            if (tokenInfo) {
                // 将 accessToken 存储到 accessStore 中
                accessStore.setAccessToken(tokenInfo.access_token);
                accessStore.setRefreshToken(tokenInfo.refresh_token);

                oauth2Store.setTokenInfo(tokenInfo);
                accessStore.setAccessCodes(oauth2Store.storePermissions);

                const { info: userInfo } = tokenInfo;
                if (accessStore.loginExpired) {
                    accessStore.setLoginExpired(false);
                } else {
                    onSuccess ? await onSuccess?.() : await router.push(userInfo.homePath || PageEnum.HOME_PATH);
                }

                if (userInfo?.name) {
                    window.$notification?.success({
                        content: "登录成功",
                        description: `欢迎回来, ${userInfo?.name ?? userInfo.nickName}`,
                        duration: 3000,
                    });
                }
            }
        } finally {
            endLoading();
        }
        return userInfo;
    }

    async function logout(redirect: boolean = true) {
        try {
            await LOGOUT();
        } catch {
            // 不做任何处理
        }
        resetAllStores();
        accessStore.setLoginExpired(false);

        // 回登录页带上当前路由地址
        await router.replace({
            path: PageEnum.LOGIN_PATH,
            query: redirect
                ? {
                      redirect: encodeURIComponent(router.currentRoute.value.fullPath),
                  }
                : {},
        });
    }

    function $reset() {
        endLoading();
    }

    return {
        $reset,
        loading,
        authLogin,
        logout,
    };
});
